//
//  OAuthViewController.m
//  01-黑马微博
//
//  Created by lanou3g on 15/9/10.
//  Copyright (c) 2015年 heima. All rights reserved.
//

#import "OAuthViewController.h"
#import "AFNetworking.h"
#import "NewFeatureViewController.h"
#import "HWTabBarViewController.h"
#import "HWAccount.h"
#import "MBProgressHUD+MJ.h"
#import "HWAccountTool.h"
@interface OAuthViewController ()<UIWebViewDelegate>

@end

@implementation OAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建webview
    UIWebView *webView = [[UIWebView alloc] init];
    webView.delegate = self;
    webView.frame = self.view.bounds;
    [self.view addSubview:webView];
    //用webview加载webview
    
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=3021046660&redirect_uri=http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
//    获得urlstring
    NSString *url = request.URL.absoluteString;
    
//    2。判断是否为毁掉地址
    NSRange range = [url rangeOfString:@"code="];
    if (range.length != 0) {
        //截取code后面的参数值
        NSInteger fromIndex = range.location + range.length;
       NSString *code =  [url substringFromIndex:fromIndex];
//     3.利用code换取一个accesstoken
        [self accessTokenWithCode:code];
        HWLog(@"%@ %@",code, url);
        //禁止加载回调地址
        return NO;
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    [MBProgressHUD showMessage:@"正在拼命请求...."];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideHUD];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
 [MBProgressHUD hideHUD];
}

/**
 *  利用code（授权成功后的请求标记）
 *
 *
 */
- (void)accessTokenWithCode:(NSString *)code{
    /**
     *  https://api.weibo.com/oauth2/access_token
     client_id 	true 	string 	申请应用时分配的AppKey。
     client_secret 	true 	string 	申请应用时分配的AppSecret。
     grant_type 	true 	string 	请求的类型，填写authorization_code
     必选 	类型及范围 	说明
     code 	true 	string 	调用authorize获得的code值。
     redirect_uri
     */
//   1. 请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//  2.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = HWAppKey;
    params[@"client_secret"] = AppSecret;
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    params[@"redirect_uri"] = @"http://www.baidu.com";
//  3.发送请求
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation * operation, NSDictionary *responseObject) {
        // 将返回的账号字典数据 --> 模型，存进沙盒
        HWAccount *account = [HWAccount accountWithDict:responseObject];
        // 存储账号信息
        [HWAccountTool saveAccountWithAccount:account];
        
//    切换根目录窗口
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window switchRootViewController];

    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        
        [MBProgressHUD hideHUD];
    }];
}
@end
